#include "maindialog.h"
#include "ui_maindialog.h"

MainDialog::MainDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::MainDialog)
{
    ui->setupUi(this);
    connect(ui->userListWidget, &QListWidget::currentRowChanged, ui->stackedWidget, &QStackedWidget::setCurrentIndex);
    addNewUser("AAAA");
    addNewUser("BBBB");

}

MainDialog::~MainDialog()
{
    delete ui;
    tcpSocket->close();
}

void MainDialog::login(QString userName)
{
    // qDebug()<< "login " << userName;
    setWindowTitle(QString("正在登录中..."));
    this->userName = userName;
    QString path = QCoreApplication::applicationDirPath();
    QFile configFile(path + "/config.json");

    if (configFile.open(QFile::ReadOnly | QIODevice::Text)){
        QTextStream in(&configFile);
        auto jsonStr = in.readAll();
        configFile.close();
        auto json = QJsonDocument::fromJson(jsonStr.toUtf8());
        auto obj = json.object();
        auto ip = obj.value("ip").toString();
        auto port = obj.value("port").toInt();
        qDebug()<< ip << "\t" << port;
        QHostAddress serverIP(ip);

        tcpSocket = new QTcpSocket(this);
        connect(tcpSocket, &QTcpSocket::readyRead, this, &MainDialog::dataReceive);
        tcpSocket->connectToHost(serverIP, port);
        isLogin = true;
        Message msg(CmdType::Login, "", "", userName);
        tcpSocket->write(msg.toByteArray());

    }else{
        qDebug() << "config file not found.";
    }

    show();
}

void MainDialog::addNewUser(QString userName)
{
    ui->userListWidget->addItem(userName);
    QTextEdit *txtMsg = new QTextEdit(this);
    txtMsg->setText(userName);
    ui->stackedWidget->insertWidget(ui->stackedWidget->count() - 1, txtMsg);
    userList.append(userName);
}

void MainDialog::removeUser(QString userName)
{
    int index = userList.indexOf(userName);
    userList.remove(index);
    ui->userListWidget->takeItem(index);
    QWidget *aWidget = ui->stackedWidget->widget(index);
    ui->stackedWidget->removeWidget(aWidget);

}

void MainDialog::dataReceive()
{
    if (tcpSocket->bytesAvailable() > 0){
        auto b = tcpSocket->readAll();
        auto msg = Message::fromByteArray(b);
        auto from = msg->getFrom();
        ui->txtMsg->setText(msg->toByteArray());
        // qDebug() << obj;
        switch (msg->getCmdType()) {
        case CmdType::Login:{
            if (from == userName){
                setWindowTitle(QString("已登录：%1").arg(userName));
            }else{
                addNewUser(from);
            }
            break;
        }
        case CmdType::Logout:{
            removeUser(from);
        }
        default:
            break;
        }

    }

}
